package javatest.guireceiver;

import com.messaging.UdpMq;
import com.messaging.events.MessageReceiveEvent;
import java.awt.Color;
import java.net.InetAddress;
import java.util.HashMap;
import javatest.Utils;
import javax.swing.BoxLayout;
import javax.swing.JPanel;

/**
 *
 * @author sad
 */
public class ReceiverForm extends javax.swing.JFrame {

    private final JPanel scroll;
    private UdpMq mq;
    private short sessionId;
    private final HashMap<Short, VideoShower> videoShowersMap = new HashMap<>();

    /**
     * Creates new form ReceiverForm
     */
    public ReceiverForm() {
        initComponents();
        scroll = new JPanel();
        scroll.setBackground(Color.red);
        scroll.setLayout(new BoxLayout(scroll, BoxLayout.Y_AXIS));
        scroll.setOpaque(true);
        scrollPane.getViewport().setView(scroll);
        initReceiver();
    }

    private void initReceiver() {
        mq = new UdpMq(5557);
        mq.start();
        mq.setMessageReceiveEvent(new MessageReceiveEvent() {

            @Override
            public void messageReceive(byte[] buffer, InetAddress sender, int port) throws Exception {
                messageReceived(buffer, sender);
            }
        });
    }

    private void messageReceived(byte[] buffer, InetAddress sender) {
        switch (buffer[0]) {
            case 0:
                processVideoFrame(buffer);
                break;
            case 1:
                processConnectClient(buffer, sender);
                break;
        }
    }

    private void processVideoFrame(byte[] buffer) {
        short clientId = Utils.arrayGetShort(buffer, 1);
        int counter = Utils.arrayGetInt(buffer, 3);
        VideoShower shower = videoShowersMap.get(clientId);
        if (shower == null) {
            // System.out.println("Client with id " + clientId + " is not found");
            return;
        }

        shower.process(buffer, counter);
    }

    private void processConnectClient(byte[] buffer, InetAddress sender) {
        short clientId = Utils.arrayGetShort(buffer, 1);
        short tSessionId = Utils.arrayGetShort(buffer, 3);
        System.out.println("Client " + sender.toString() + " tries to connect. ClientId=" + clientId);
        if (tSessionId != sessionId) {
            System.out.println("Start new Session");
            sessionId = tSessionId;
            sessionLabel.setText("" + sessionId);
            videoShowersMap.clear();
            scroll.removeAll();
        }
        if (videoShowersMap.containsKey(clientId)) {
            return;
        }

        VideoShower shower = new VideoShower();
        if (clientId == 3) {
            shower.setShouldAdd(true);
        }
        videoShowersMap.put(clientId, shower);
        clientCountLabel.setText("" + videoShowersMap.size());
        scroll.add(shower);
        scroll.revalidate();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollPane = new javax.swing.JScrollPane();
        jLabel1 = new javax.swing.JLabel();
        sessionLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        clientCountLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Video Receiver");

        jLabel1.setText("SessionId:");

        sessionLabel.setText("   ");

        jLabel2.setText("Clients Count");

        clientCountLabel.setText(" ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(clientCountLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(sessionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(sessionLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(clientCountLabel))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel clientCountLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JLabel sessionLabel;
    // End of variables declaration//GEN-END:variables
}
